/**
 * BuddyAge main.js
 */

function initPersonList() {
	$.post("app/buddy", {
		format : "XML"
	}, personListHandler, "xml");
}

function selectPersonHandler(event) {
	// href is of the form "#id". Extract the id.
	var id = $(this).attr("href").substring(1);
	// Check the id? id.match(/\d+/).
	// Get the person's information
	$.post("app/buddy/" + id, {
		format : "XML"
	}, viewPersonInformationHandler, "xml");
	event.preventDefault();
}

function increaseAgeHandler(event) {
	setMessage("Increasing age.");
	var incAgeForm = $("#ViewPerson form");
	var inputs = $(":input", incAgeForm);
	var url = incAgeForm.attr("action"); // this was set earlier.
	// $.post(url, inputs, viewPersonInformationHandler, "xml");
	$.ajax({
		  type: 'POST',
		  url: url,
		  data: inputs,
		  success: viewPersonInformationHandler,
		  error: increaseAgeErrorHandler,
		  dataType: 'xml'
		});
	event.preventDefault();
}

function increaseAgeErrorHandler(XMLHttpRequest, textStatus, errorThrown) {
	$("#ViewPerson .person_age").text("?");
	setMessage("Increasing age failed. Refresh the persons information and retry.", "important");
}

function setMessage(text, classAttr) {
	var footer = $("#footer");
	var footerP = $("p", footer);
	var msgCount = footerP.length;

	footer.empty(); // remove children nodes.
	if(msgCount >= 1) {
		footer.append(footerP[msgCount - 1]);
	}
	footer.append("<p></p>");
	var lastMsg = footer.children(':last');
	lastMsg.text(text);
	if(classAttr) {
		lastMsg.addClass(classAttr);
	}
}

function viewPersonInformationHandler(xmlData) {
	// <span class="person_name">Person's Name</span> is <span class="person_age">999</span> years old and has <span class="person_buddy">Buddy_SPec</span> buddy.
	var person = $("person", xmlData);
	// Set the name and age span elements.
	var name = $("name", person).text();
	$("#ViewPerson .person_name").text(name);
	$("#ViewPerson .person_age").text($("age", person).text());

	// Things are a bit more complicated for buddy since we need
	// to access the buddy information if this person has a buddy.
	
	var buddyId = $("buddy", person).text();
	// $("#ViewPerson .person_buddy").text("[looking up buddy information]");
	if(buddyId == "") {
		$("#ViewPerson .person_buddy").text("no");
	} else {
		$.post("app/buddy/" + buddyId, {
			format : "XML"
		}, function(xml) { 
			setMessage("Getting buddy info.");
			var buddy = $("person", xml);
			var buddyId = $("id", buddy).text()
			var buddyRef = '<a href="#' + buddyId + '">' + $("name", buddy).text() + '</a>';
			$("#ViewPerson .person_buddy").html(buddyRef);
			$("#ViewPerson .person_buddy a").click(selectPersonHandler);
		}, "xml");
	}
	
	var incAgeForm = $("#ViewPerson form");
	incAgeForm.attr("action", "app/buddy/" + $("id", person).text());
	incAgeForm.find("[name='version']").val($("version", person).text());
	incAgeForm.unbind('submit'); // unbind any previous handlers
	incAgeForm.bind('submit', increaseAgeHandler);

	$("#NoPersonToView").hide();
	$("#ViewPerson").show();
	setMessage("Viewing " + name + "'s information.");
}

function personListHandler(xmlData) {
	setMessage("Retrieving person list.");
	var ul = $("#sidebar1 ul"); // get the sidebar1 <ul> DOM element.
	ul.empty();	// remove children nodes.
	var people = $("person", xmlData);
	// for each person, add an <li> element
	for ( var i = 0; i < people.length; i++) {
		var id = $("id", people[i]).text();
		var name = $("name", people[i]).text();
		var a = '<a href="#' + id + '">' + name + '</a>';
		ul.append('<li>' + a + '</li>');
	}
	// Set the onclick handler for all <a> elements.
	$("#sidebar1 ul li a").click(selectPersonHandler);
	setMessage("Retrieved " + people.length + " people.");
}

function buddyAgeSetup() {
	$("#ViewPerson").hide(); // Hide this pane until there is something to view.
	initPersonList();
}

/* --- */

$(document).ready(buddyAgeSetup);